/*
 * File Name：AppUtils.java
 * Copyright：Copyright 2008 - 2012 CiWong.Inc. All Rights Reserved.
 * Description： AppUtils.java
 * Modify By：PLA-GLLENG
 * Modify Date：2012-10-30
 * Modify Type：Add
 */
package com.ciwong.ciwongwrite.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;

import com.ciwong.ciwongwrite.R;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;


/**
 * 习网app工具类
 *
 * @author PLA-GLLENG
 * @version ciwong v.1.0 2012-10-30
 * @since ciwong v.1.0
 */
public class CWUtils {
    private static LayoutInflater inflater;

    /**
     * 实例化布局文件 TODO
     *
     * @param mContext 上下文
     * @param resource 布局文件资源ID
     * @param root     根布局
     * @return view
     */
    public static View getViewInstace(Context mContext, int resource,
                                      ViewGroup root) {
        if (inflater == null) {
            inflater = (LayoutInflater) mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        return inflater.inflate(resource, root);
    }

    /**
     * 将日期字符串格式转换为long数据
     *
     * @param dateStr 日期格式字符串
     * @return 日期长整型
     */
    public static long convertTime(String dateStr) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return format.parse(dateStr).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取当前日期转为yyyyMMdd格式
     *
     * @return
     */
    public static String getReadTime(long startTime) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            String dateString = format.format(startTime);
            return dateString;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String convertDKTime(long dateLong) {
        try {
            Date date = new Date(dateLong);
            SimpleDateFormat format = new SimpleDateFormat(
                    "yyyy-MM-dd HH:mm");
            return format.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取系统当前时间
     *
     * @param type 要返回时间的格式（0代表yyyy-MM-dd HH:mm:ss， 1代表yyyy-MM-dd）
     * @return 返回一个String类型的时间
     */
    public static String getSysTime(int type) {
        SimpleDateFormat formatter = null;
        if (type == 0) {
            formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        } else {
            formatter = new SimpleDateFormat("yyyy-MM-dd");
        }
        Date curDate = new Date(System.currentTimeMillis());
        String str = formatter.format(curDate);
        return str;
    }

    /**
     * 获取时间段日期的数组
     *
     * @param dateTime 时间段的结束日期
     * @param size     时间段的长度
     * @return 一个某个时间段中所有日期的String数组
     */
    public static String[] getPeriodTime(String dateTime, int size) {
        long l = CWUtils.convertTime(dateTime);
        Date date = new Date();
        date.setTime(l);
        Calendar c = Calendar.getInstance();
        String[] period = new String[size];
        for (int i = 0; i < size; i++) {
            c.setTime(date);
            c.add(Calendar.DAY_OF_MONTH, -i);
            period[size - i - 1] = c.get(Calendar.YEAR) + "-"
                    + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DATE);
        }
        return period;
    }

    /**
     * 对比时间是否已过
     *
     * @param publishDate 完成时间
     * @return 返回true为已过期，反之未过期
     */
    public static boolean contrastTime(String publishDate) {

        long c = convertTime(getSysTime(0));
        long l = convertTime(publishDate);
        if (c > l)
            return true;
        return false;
    }

    /**
     * 对比时间是否已过
     *
     * @return 返回true为已过期，反之未过期
     */
    public static boolean contrastTime(long date) {
        return System.currentTimeMillis() > date;
    }

    /**
     * 转换成做完作业用了多长时间
     *
     * @param taskWorkLong 用了多少毫秒
     * @return 返回一个以HH:mm:ss类型的String
     */
    public static String transformTime(int taskWorkLong) {
        taskWorkLong /= 1000;
        int minute = taskWorkLong / 60;
        int hour = minute / 60;
        int second = taskWorkLong % 60;
        minute %= 60;
        return String.format("%02d:%02d:%02d", hour, minute, second);
    }

    /**
     * md5加密
     *
     * @param str
     * @return
     */
    public static String md5(String str) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");

            messageDigest.reset();

            messageDigest.update(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            System.out.println("NoSuchAlgorithmException caught!");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        byte[] byteArray = messageDigest.digest();

        StringBuffer md5StrBuff = new StringBuffer();

        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
                md5StrBuff.append("0").append(
                        Integer.toHexString(0xFF & byteArray[i]));
            else
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
        }

        return md5StrBuff.toString();
    }

    /**
     * md5加密
     *
     * @param
     * @return
     */
    public static String md5(byte[] target, int len) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");

            messageDigest.reset();

            messageDigest.update(target, 0, len);
        } catch (NoSuchAlgorithmException e) {
            System.out.println("NoSuchAlgorithmException caught!");
        }

        byte[] byteArray = messageDigest.digest();

        StringBuffer md5StrBuff = new StringBuffer();

        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
                md5StrBuff.append("0").append(
                        Integer.toHexString(0xFF & byteArray[i]));
            else
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
        }

        return md5StrBuff.toString();
    }

    /**
     * 日期转换(yyyy-MM-dd HH:mm:ss)<br />
     * 转换中出现异常则返回null
     *
     * @param dateLong 日期长整型
     * @return
     */
    public static String formatDate1(long dateLong) {
        try {
            Date date = new Date(dateLong);
            SimpleDateFormat format = new SimpleDateFormat(
                    "yyyy-MM-dd HH:mm:ss");
            return format.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 日期转换(yyyy年MM月dd日)<br />
     * 转换中出现异常则返回null
     *
     * @param dateLong 日期长整型
     * @return
     */
    public static String formatDay(long dateLong) {
        try {
            Date date = new Date(dateLong);
            SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
            return format.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将图片放大或缩小
     *
     * @param src          源图片
     * @param targetWidth  目标宽
     * @param targetHeight 目标高
     * @return 转换后的图片
     */
    public static Bitmap matrix(Bitmap src, int targetWidth, int targetHeight) {
        int w = src.getWidth();
        int h = src.getHeight();
        float scaleWidth = ((float) targetWidth) / ((float) w);
        float scaleHeight = ((float) targetHeight) / ((float) h);
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap target = Bitmap.createBitmap(src, 0, 0, w, h, matrix, true);
        return target;
    }

    /**
     * 将图片放大或缩小
     *
     * @param src         源图片
     * @param simpleScale 放大缩小比例
     * @return 转换后的图片
     */
    public static Bitmap matrix(Bitmap src, float simpleScale) {
        int w = src.getWidth();
        int h = src.getHeight();
        Matrix matrix = new Matrix();
        matrix.postScale(simpleScale, simpleScale);
        Bitmap target = Bitmap.createBitmap(src, 0, 0, w, h, matrix, true);
        return target;
    }

    /**
     * 隐藏软键盘
     *
     * @param mActivity Activity
     */
    public static void hideSoftInput(View focusView, Activity mActivity) {
        ((InputMethodManager) mActivity
                .getSystemService(Activity.INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(focusView.getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 显示软键盘
     *
     * @param foucsView 焦点控件
     * @param mActivity Activity
     */
    public static void showSoftInput(View foucsView, Activity mActivity) {
        ((InputMethodManager) mActivity
                .getSystemService(Activity.INPUT_METHOD_SERVICE))
                .showSoftInput(foucsView, 0);

    }

    /**
     * 日期转换(yyyy-MM-dd HH:mm:ss)<br />
     * 转换中出现异常则返回null
     *
     * @param dateLong 日期长整型
     * @return
     */
    public static String formatTime(long dateLong) {
        try {
            Date date = new Date(dateLong);
            SimpleDateFormat format = new SimpleDateFormat("HH:mm");
            return format.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 日期转换(MM-dd HH:mm)<br />
     * 转换中出现异常则返回null
     *
     * @param dateLong 日期长整型
     * @return
     */
    public static String formatDate3(long dateLong) {
        try {
            Date date = new Date(dateLong);
            SimpleDateFormat format = new SimpleDateFormat("MM-dd HH:mm");
            return format.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取时间，以今天，昨天的形式展示
     *
     * @param ceartmillis
     * @return
     */
    public static String formatDate4(long ceartmillis, Activity mActivity) {
        String dateString;
        Date date = new Date(ceartmillis);
        Date newdate = new Date();
        Calendar calendar = Calendar.getInstance(Locale.CHINA);
        calendar.setTime(date);
        int _dateday = newdate.getDate() - calendar.get(Calendar.DAY_OF_MONTH);
        if (_dateday == 0) {
            dateString = mActivity.getText(R.string.today).toString() + " "
                    + formatTime(ceartmillis);
        } else if (_dateday == 1) {
            dateString = mActivity.getText(R.string.yestoday).toString() + " "
                    + formatTime(ceartmillis);
        } else {
            dateString = formatDate3(ceartmillis);
        }

        return dateString;
    }

    public static String formatDate5(long ceartmillis) {
        SimpleDateFormat formatter1 = new SimpleDateFormat("MM-dd");
        String format = formatter1.format(ceartmillis);
        StringBuilder stringBuilder = new StringBuilder();
        try {
            String[] split = format.split("-");
            for (int i = 0; i < split.length; i++) {
                if (split[i].startsWith("0")) {
                    String substring = split[i].substring(1);
                    stringBuilder.append(substring);
                } else {
                    stringBuilder.append(split[i]);
                }

                if (i < split.length - 1) {
                    stringBuilder.append("-");
                }

            }
        } catch (Exception e) {
            stringBuilder.append(format);
        }
        return stringBuilder.toString();
    }
    public static String formatDate5two(long ceartmillis) {
        SimpleDateFormat formatter1 = new SimpleDateFormat("MM月dd日");
        String format = formatter1.format(ceartmillis);
        StringBuilder stringBuilder = new StringBuilder();
        try {
            String[] split = format.split("-");
            for (int i = 0; i < split.length; i++) {
                if (split[i].startsWith("0")) {
                    String substring = split[i].substring(1);
                    stringBuilder.append(substring);
                } else {
                    stringBuilder.append(split[i]);
                }

                if (i < split.length - 1) {
                    stringBuilder.append("-");
                }

            }
        } catch (Exception e) {
            stringBuilder.append(format);
        }
        return stringBuilder.toString();
    }
    public static String formatDate6(long ceartmillis) {
        SimpleDateFormat formatter1 = new SimpleDateFormat("M月d日");
        String format = formatter1.format(ceartmillis);
       /* StringBuilder stringBuilder = new StringBuilder();
        try {
            String[] split = format.split("-");
            for (int i = 0; i < split.length; i++) {
                if(split[i].startsWith("0")){
                    String substring = split[i].substring(1);
                    stringBuilder.append(substring);
                }else{
                    stringBuilder.append(split[i]);
                }

                if(i<split.length-1){
                    stringBuilder.append("-");
                }

            }
        } catch (Exception e) {
            stringBuilder.append(format);
        }*/
        return format;
    }

    /**
     * 获取时间，以星期几 的形式展示
     *
     * @param ceartmillis
     * @return
     */
    public static String formatDateToWeek(long ceartmillis) {
        String[] weekOfDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        try {

            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(ceartmillis);
            int w = calendar.get(Calendar.DAY_OF_WEEK) - 1;
            if (w < 0) {
                w = 0;
            }

            return weekOfDays[w];

        } catch (Exception e) {
            e.getStackTrace();
        }
        return "";
    }

    public static String formatDateToWeek2(long ceartmillis) {
        String[] weekOfDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        try {

            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(ceartmillis);
            int w = calendar.get(Calendar.DAY_OF_WEEK) - 1;
            if (w < 0) {
                w = 0;
            }

            return weekOfDays[w];

        } catch (Exception e) {
            e.getStackTrace();
        }
        return "";
    }

    /**
     * 作业布置时间
     *
     * @param ceartmillis
     * @return
     */
    public static String getWorkTime(long ceartmillis) {
        String dateString = "";
        long delmillis = (System.currentTimeMillis() - ceartmillis) / 1000L;
        Date newdate = new Date();
        Calendar newcalendar = Calendar.getInstance(Locale.CHINA);
        newcalendar.setTime(newdate);
        Date date = new Date(ceartmillis);
        Calendar calendar = Calendar.getInstance(Locale.CHINA);
        calendar.setTime(date);
        int dateday = newcalendar.get(Calendar.DAY_OF_YEAR) - calendar.get(Calendar.DAY_OF_YEAR);
        SimpleDateFormat formatter = new SimpleDateFormat("MM-dd HH:mm");
        SimpleDateFormat formatter1 = new SimpleDateFormat("MM-dd");
        SimpleDateFormat formatter2 = new SimpleDateFormat("HH:mm");
        if (delmillis / 60L / 60L / 24L >= 0L && delmillis / 60L / 60L / 24L < 4L) {
            if (dateday == 0) {
                if (delmillis >= 0L && delmillis <= 60L) {
                    dateString = "刚刚";
                } else if (delmillis > 60L && delmillis <= 3600L) {
                    dateString = delmillis / 60L + "分钟前";
                } else {
                    dateString = "今天 (" + formatDateToWeek2(ceartmillis) + ") " + formatter2.format(ceartmillis);
                }
            } else if (dateday == 1) {
                dateString = "昨天 (" + formatDateToWeek2(ceartmillis) + ") " + formatter2.format(ceartmillis);
            } else if (dateday == 2) {
                dateString = "前天 (" + formatDateToWeek2(ceartmillis) + ") " + formatter2.format(ceartmillis);
            } else {
                dateString = formatDate5(ceartmillis) + " (" + formatDateToWeek2(ceartmillis) + ") " + formatter2.format(ceartmillis);
            }
        } else {
            dateString = formatDate5(ceartmillis) + " (" + formatDateToWeek2(ceartmillis) + ") " + formatter2.format(ceartmillis);
        }

        return dateString;
    }

    /**
     * 作业截止时间
     *
     * @param ceartmillis（秒）
     * @return
     */
    public static String getWorkFinishTime(long ceartmillis) {
        String dateString = "";
        SimpleDateFormat formatter1 = new SimpleDateFormat("MM月dd日");
        SimpleDateFormat formatter2 = new SimpleDateFormat("HH:mm");
        dateString = formatter1.format(ceartmillis * 1000) + " (" + formatDateToWeek2(ceartmillis * 1000) + ") " + formatter2.format(ceartmillis * 1000);
        return dateString;
    }

    /**
     * 作业布置截止倒计时时间
     *
     * @param submillis 时间
     * @return
     */
    public static String getWorkStopTime(long submillis) {
        String dateString = "";
        long daymillis = 60L * 60L * 24L;//一天的秒数
        long hourmillis = 60L * 60L;//一小时的秒数
        long minutemillis = 60L;//一分钟的秒数
        if (submillis < daymillis) {
            //小于一天
            if (submillis >= 0L && submillis <= minutemillis) {
                dateString = submillis + "秒";
            } else if (submillis > minutemillis && submillis <= hourmillis) {
                dateString = submillis / minutemillis + "分钟";
            } else {
                dateString = submillis / hourmillis + "小时" + (submillis % hourmillis) / minutemillis + "分钟";
            }
        } else {
            //大于一天
            dateString = submillis / daymillis + "天" + (submillis % daymillis) / hourmillis + "小时" + ((submillis % daymillis) % hourmillis) / 60 + "分钟";
        }

        return dateString;
    }

    /**
     * widget 作业页面的时间（日期)
     *
     * @param ceartmillis
     * @return
     */
    public static String getWidgetWorkTimeDay(long ceartmillis) {
        String dayString = "";
        long delmillis = (System.currentTimeMillis() - ceartmillis) / 1000L;
        Date newdate = new Date();
        Calendar newcalendar = Calendar.getInstance(Locale.CHINA);
        newcalendar.setTime(newdate);
        Date date = new Date(ceartmillis);
        Calendar calendar = Calendar.getInstance(Locale.CHINA);
        calendar.setTime(date);
        int dateday = newcalendar.get(Calendar.DAY_OF_YEAR) - calendar.get(Calendar.DAY_OF_YEAR);
        if (delmillis / 60L / 60L / 24L >= 0L && delmillis / 60L / 60L / 24L < 4L) {
            if (dateday == 0) {
                if (delmillis >= 0L && delmillis <= 60L) {
                    dayString = "刚刚";
                } else if (delmillis > 60L && delmillis <= 3600L) {
                    dayString = delmillis / 60L + "分钟前";
                } else {
                    dayString = "今天 (" + formatDateToWeek2(ceartmillis) + ") ";
                }
            } else if (dateday == 1) {
                dayString = "昨天 (" + formatDateToWeek2(ceartmillis) + ") ";
            } else if (dateday == 2) {
                dayString = "前天 (" + formatDateToWeek2(ceartmillis) + ") ";
            } else {
                dayString = formatDate6(ceartmillis) + " (" + formatDateToWeek2(ceartmillis) + ") ";
            }
        } else {
            dayString = formatDate6(ceartmillis) + " (" + formatDateToWeek2(ceartmillis) + ") ";
        }
        return dayString;
    }

    /**
     * widget 作业页面的时间（时分)
     *
     * @param ceartmillis
     * @return
     */
    public static String getWidgetWorkTimeHour(long ceartmillis) {
        String hourString = "";
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
        hourString = formatter.format(ceartmillis);
        return hourString;

    }


    /**
     * dip转px
     *
     * @param context
     * @param dipValue
     * @return
     */
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * px转dip
     *
     * @param context
     * @param pxValue
     * @return
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


}
